const db = require('../db/dbs')

module.exports = {
    async addOpenidAndUserInfo(OpenID, NickName, ProfilePicture) {
        try {
            const sql = `
                INSERT INTO user (OpenID, NickName, ProfilePicture, LastLanding, Seed, Water, Fertilizer, Coin, Lv)
                VALUES (?, ?, ?, NOW(), 0, 0, 0, 0, 0)
                ON DUPLICATE KEY UPDATE 
                    NickName = VALUES(NickName), 
                    ProfilePicture = VALUES(ProfilePicture),
                    LastLanding = NOW(),
                    Seed = VALUES(Seed),
                    Water = VALUES(Water),
                    Fertilizer = VALUES(Fertilizer),
                    Coin = VALUES(Coin),
                    Lv = VALUES(Lv)
            `;
            const values = [OpenID, NickName, ProfilePicture];
            const result = await db.query(sql, values);
            console.log('添加 OpenID 和用户信息成功:', result);
            return result; // 可根据需要返回执行结果
        } catch (error) {
            throw new Error('添加 OpenID 和用户信息失败: ' + error.message);
        }
    },
    async findUserByOpenid(OpenID) {
        try {
            let res = await db.query("SELECT * FROM user WHERE OpenID=?", [OpenID]);
            console.log('查询 OpenID 对应的用户信息成功:', res);
            return res.length > 0 ? res[0] : null;
        } catch (error) {
            throw new Error('查询 OpenID 对应用户信息失败: ' + error.message);
        }
    },
    async updateLastLoginTime(OpenID) {
        try {
            const sql = "UPDATE user SET LastLanding = NOW() WHERE OpenID = ?";
            const result = await db.query(sql, [OpenID]);
            console.log('更新最后登录时间成功:', result);
            return result; // 可根据需要返回执行结果
        } catch (error) {
            throw new Error('更新最后登录时间失败: ' + error.message);
        }
    },
    // 通过 StaticID 获取 StaticURL
    async getStatic(StaticID) {
        const selectQuery = `SELECT StaticURL FROM static WHERE StaticID = ?`;
        try {
            const rows = await db.query(selectQuery, [StaticID]);
            if (rows.length > 0) {
                return rows[0].StaticURL;
            } else {
                throw new Error(`找不到StaticID为 ${StaticID} 的数据链接`);
            }
        } catch (error) {
            throw new Error(`无法获取数据链接: ${error.message}`);
        }
    },
}